#include "SpiProtocol.h"

SpiProtocol::SpiProtocol(SoftwareSpi& s)
{
	spi= s;
	input = Queue<unsigned char>();
	output = Queue<unsigned char>();
}

void SpiProtocol::writeByte(unsigned char data){input.push(data);}
void SpiProtocol::write(void* data, unsigned long int length)
{
	unsigned int i = 0;
	for(i = 0; i < length; i++)
	{
		unsigned char* d = (unsigned char*) (data + i);
		unsigned char temp = *d;
		input.push(temp);
	}
}
unsigned char SpiProtocol::readByte(){return output.pop();}

void* SpiProtocol::read(unsigned long int length)
{
	//get the data I want to read from the queue now.
	void* mem = malloc(length);
	unsigned int i = 0;
	for(i = 0; i < length; i++)
	{
		unsigned char* t = (unsigned char*) (mem + i);
		if(output.empty()==1)
			break;
		*t = output.pop();
	}
	if(i != length)
		for(i = i; i < length; i++)
		{
			unsigned char* t = (unsigned char*)
				 (mem+i);
			*t = 0x00;
		}
	return mem;
}


unsigned char SpiProtocol::full(){return 0;}
unsigned char SpiProtocol::empty(){ return output.empty();}
void SpiProtocol::config(){}
void SpiProtocol::run()
{
	if(spi.getFinished()==true)
	{
		//get the new expected output first
		BitArray a = spi.get();
		unsigned char answer = 0x00;
		unsigned char j = 0;	
		for(j = 0; j < 8; j++)
			answer = SetBit(answer, j, a[j].getBit());
		//add to output.
		output.push(answer);
		//set the new input.
		unsigned char t;
		if(input.empty()==1)
			t = 0;
		else
			t = input.pop();
		//create the bit array now
		BitArray array = BitArray(8);
		unsigned char i = 0;	
		for(i = 0; i < 8; i++)
			array[i].setBit(GetBit(t, i));
		//now after creating set
		spi.set(array);
	}
	//now do the spi stuff
	spi.run();
}


